<template>
	<layout class="wallet-wrap" title="抽奖">
		<view class="content">
			<view class="lottery">
				<wheel :prizes="prizes" :size="700" :duration="5000" @run="onWheelClick"
					@done="onWheelDone" ref="luckyWheel" :lightImgs="lightImages" customStyle="borderRadius: 50%;">
					<template v-slot:bg>
						<image src="/static//wheel/tzbj.png" style="width: 100%; height: 100%" />
					</template>
					<template v-slot:pointer>
						<image src="/static//wheel/tan.png" style="width: 212rpx" mode="widthFix" @click="startWheel"/>
					</template>
				</wheel>
				<view class="wheeltime"><view style="text-align: center;">{{wheelCount}}</view></view>
			</view>
			<view class="raffle_container">
				<view class="raffle_bar">
					<view
						v-for="(item, index) in tabs"
						:key="index"
						class="raffle_title_item"
						:class="{ active: activeIndex === index }"
						@click="switchTab(index)"
					>
						{{ item.title }}
					</view>
				</view>
				<view class="raffle_content">
					<view v-if="activeIndex === 0">
						<template v-if="loading.record">
							<view class="loading_text">加载中...</view>
						</template>
						<template v-else>
							<view
								class="raffle_records"
								v-for="(item, index) in recordList"
								:key="index"
							>
								<view class="item_record">
									<view class="avatar">
										<image class="avatar_name" mode="aspectFit" :src="item.avatar"  ></image>
									</view>
									<view class="detail">
										<view class="nametime">
											<view class="name hidden">{{item.name}}</view>
											<view class="time">{{item.time}}</view>
										</view>
										<view class="desc hidden">{{item.desc}}</view>
									</view>
									<!-- <view class="product"> -->
										<image class="product" mode="aspectFit" :src="item.image" ></image>
									<!-- </view> -->
								</view>
							</view>
						</template>
						
					</view>
					<view v-if="activeIndex === 1">
						  <scroll-view class="rules-content" scroll-y>
							<view class="rule-item" >
							  <text class="rule-text">{{rules}}</text>
							</view>
						  </scroll-view>
					</view>
					<view v-if="activeIndex === 2">
						<template v-if="loading.activity">
							<view class="loading_text">加载中...</view>
						</template>
						<template v-else>
							<view class="raffle_task">
								<view class="item_task">
									<view class="detail">
										<view class="title">{{prizeChance.title}}</view>
										<view class="desc hidden">{{prizeChance.desc}}</view>
									</view>
									<button class="task_btn" @click="handleBuyChance">
										{{ prizeChance.btnText }}
									</button>
								</view>
							</view>
							<!-- <view class="raffle_task">
								<view class="item_task">
									<view class="detail">
										<view class="title">{{freeLogin.title}}</view>
										<view class="desc hidden">{{freeLogin.desc}}</view>
									</view>
									<button
										class="task_btn"
										:class="{
											'disabled': !freeLogin.isGeted
										}"
										:disabled="!freeLogin.isGeted || loading.activity"
										@click="handleFreeLogin"
									>
										{{ freeLogin.btnText }}
									</button>
								</view>
							</view> -->
							<!-- <view
								class="raffle_task"
								v-for="(item, index) in taskList"
								:key="index"
							>
								<view class="item_task">
									<view class="detail">
										<view class="title">{{item.title}}</view>
										<view class="desc hidden">{{item.desc}}</view>
									</view>
									<button
										class="task_btn"
										:class="{
											'disabled': item.isCompleted
										}"
										open-type="share"
										:disabled="item.isCompleted || loading.activity"
										@click="handleTaskAction(item.id)"
									>
										{{ item.isCompleted ? '已完成' : item.btnText }}
									</button>
								</view>
							</view> -->
						</template>
					</view>
				</view>
			</view>
		</view>
	</layout>
</template>

<script>
    import layout from '@/sheep/components/s-layout/s-layout';
	import wheel from '../components/wheel';
	import request from '@/sheep/request';
	import sheep from '@/sheep';
	export default {
		components: {
			wheel,
			layout
		},
		data() {
			return {
				activeIndex: 1, //当前选中索引
				pos: 1, // 转盘位置
				prizeId: '2',
				buyChancePrice: 1, //每次机会对应价格
				tabs: [
					{ title: '中奖记录' },
					{ title: '抽奖规则' },
					{ title: '抽奖活动' },
				],
				loading: {
					record: false,
					rules: false,
					activity: false
				},
				rules: '',
				wheelCount:0,
				noTime:0,
				lightImages: ['/static/wheel/tpoint1.png', '/static//wheel/tpoint2.png'],	
				prizes: [{
						name: '积分',
						image: '/static//wheel/thb.png',
						pro: '50积分',
					},
					{
						name: '谢谢参与',
						image: '/static//wheel/thb.png',
						pro: '15元优惠券',
					},
					{
						name: '办公用品',
						image: '/static/wheel//thb.png',
						pro: '机械键盘',
					},
					{
						name: '生活用品',
						image: '/static//wheel/thb.png',
						pro: '化妆刷',
					},
				],
				recordList: [],
				rules: [],
				prizeChance: { title: '抽奖次数购买', desc: '3.99元/次，点击购买', btnText: '购买' },
				freeLogin: { title: '每日免费抽奖', desc: '每日可免费拉取一次抽奖机会', isGeted: true, btnText: '领取' },
				taskList: [
					{ title: '邀请好友完成任务', desc: '邀请3位好友参与活动',id:1, isCompleted: false, btnText: '去分享'},
					// { title: '测试按钮专用', desc: '邀请3位好友参与活动', isCompleted: true, btnText: '未接受'}
				],
				ralUrl:'https://www.xcyez.com/file-hub/bc16626b2c6b304c52f4e633bb45300c5142fb907caaf4079a936d7a4ac8ed85.png'
			}
		},
		onLoad() {
			this.getPrizeById()
		},
		onShow(){
			this.init()
		},
		methods: {
			hasData(index){
				switch(index){
					case 0: return this.recordList.length > 0
					case 1: return this.rules.length > 0
					case 2: return this.taskList.length > 0
					default: return false
				}
			},
			async switchTab(index) {
				if(this.activeIndex === index && this.hasData(index)) return;
				this.activeIndex = index
				switch(index){
					case 0:
						await this.getPrizeRecordHis(this.prizeId)
						break
					case 2:
						await this.getFreeInfo(this.prizeId)
						break
				}
			},
			// 获取用户抽奖次数
			async init(){
				const res = await request({
					url: '/app/prize/getMyPrizeChance', 
					method:'GET',
					params: {
						prizeId: this.prizeId,
					},
				})
				this.wheelCount=res.data.remainCount
			},
			// 获取最新抽奖活动
			async getPrizeById(){
				const res = await request({
					url: '/app/prize/list', 
					method:'GET',
					params: {
						status: '1',
					},
				})
				this.prizeId = res?.data[0]?.prizeId || '2'
				try {
					const resDetail = await request({
						url: '/app/prize/getPrizeDetailById', 
						method:'GET',
						params: {
							prizeId: this.prizeId,
						},
					})
					if(resDetail.code === 0 && resDetail.data){
						this.rules = resDetail.data.rules
						this.buyChancePrice = resDetail.data.otherRules?.buyChancePrice
						this.prizes = resDetail.data.awardList?.map(item => ({
							image: item.awardPicUrl || this.ralUrl,
							name: item.awardName,
							pro: item.awardName,
							id: item.id
						}))
						this.prizes.unshift({
							image: this.ralUrl,
							name:'谢谢参与',
							pro:'',
							id:0
						})
					} else {
						console.error('获取当前活动详情异常')
						uni.showToast({ title: '加载失败', icon: 'none'})
					}
				} catch (error) {
					console.error('获取当前活动详情异常')
					uni.showToast({ title: '加载失败', icon: 'none'})
				}

			},
			// 查看中奖名单
			async getPrizeRecordHis(id){
				this.loading.record = true;
				try {
					const res = await request({
						url: '/app/activityRecordHis/list', 
						method:'GET',
						params: {
							prizeId: id,
						},
					})
					// console.log('getPrizeRecordHis', res);
					if(res.code === 0 && res.data){
						this.recordList = res.data.map(item => ({
							avatar: item.userAvatar,
							name: item.userName,
							desc: `获得了${item.awardName}`,
							time: item.createTime,
							image: item.awardTypeName=='商品'?item.awardPhotoUrl:this.ralUrl
						}))
					} else {
						uni.showToast({ title: '加载失败', icon: 'none'})
					}
				} catch (error) {
					uni.showToast({ title: '加载失败', icon: 'none'})
				} finally {
					this.loading.record = false
				}
			},
			// 查看用户每日领取的状态
			async getFreeInfo(id){
				try{
					const res = await request({
						url:'app/prize/checkDaylyChance',
						method:'GET',
						params: {
							prizeId: id,
						},
					});
					if(res.code === 0){
						this.freeLogin.isGeted = res.data
						this.freeLogin.btnText = this.freeLogin.isGeted ? '领取' : '已领取'
					} else {
						console.error('获取每日领取异常')
						uni.showToast({ title: res.msg, icon: 'none'})
					}
				} catch (error) {
					console.error('获取每日领取异常')
					uni.showToast({ title: '加载失败', icon: 'none'})
				}
			},
			async handleFreeLogin(){
				this.freeLogin.isGeted = false
				this.freeLogin.btnText = '已领取'
				const res = await request({
					url:'/app/prize/getDaylyFreeChance',
					method:'GET',
					params: {
						prizeId: this.prizeId,
					},
				})
				this.init()
				// console.log('handleFreeLogin', res)
			},
			handleBuyChance(){
				uni.navigateTo({
					url: '/pages/pay/buyPrizeChance',
					success: (res) => {
						res.eventChannel.emit('sendData', {
							chanceInfo: {
								prizeId: this.prizeId,
								buyChancePrice: this.buyChancePrice
							}
						})
					}
				})
			},
			async handleTaskAction(taskID){
				
			},
			async startWheel() {
				let that = this;
				if(this.wheelCount==0){
					uni.showModal({
						title:'次数已用完',
						content:'请购买次数',
						confirmText:'去购买',
						success (res) {
						    if (res.confirm) {
						       that.handleBuyChance()
						    } 
						  }
					})
					return;
				}
				let res =''
				setTimeout(async()=>{
			    	res = await request({
			    		url:'/app/prize/clickPrize',
			    		method:'GET',
			    		params: {
			    			prizeId: this.prizeId,
			    		},
			    	})
					
					if(res.data){
						this.pos = this.prizes.findIndex(prize => prize.id === res.data.id)
						this.$refs.luckyWheel.run(this.pos);
						setTimeout(() => {
							uni.showModal({
								title:'恭喜你',
								content:"抽中了“"+res.data.awardName+'”,请及时领取'
							})
						}, 4000)
					}else{
						this.$refs.luckyWheel.run(0);
						setTimeout(() => {
							uni.showToast({
								title:'很遗憾'+res.msg
							})
						}, 4000)
					}
					this.init()
				},0)
			},
			onWheelClick() {
				console.log('用户点击了转盘');
				// this.$refs.luckyWheel.run(this.pos);
			},
			onWheelDone(prize) {
				console.log('抽奖结束，中奖奖品：', prize);
			},
		}
	}
</script>

<style lang="scss" scoped>
	.content{
		display: flex;
		flex-direction: column;
		align-items: center;
		background-color: aliceblue;
		min-height: 100vh;
		height: 100%;
		padding: 20upx;
	}
	.lottery {
	    position: relative;
	    display: inline-block;
	    width: 700rpx;
	    height: 700rpx;
	}
	.wheeltime{
		position: absolute;
		z-index: 9999;
		top: 385upx;
		left: 310upx;
		width:80upx;
		color: white;
		font-weight: bold;
		text-align: center;
	}
	.rule{
		position: absolute;
		z-index: 9999;
		font-weight: 300;
		font-size: 25upx;
		color: #000000 !important;
		top: 5upx;
		right:13upx;
		color: white;
		font-weight: bold;
	}
	.inline{
		display: flex;
		justify-content: center;
		align-items: center;
	}
	.hidden{
		white-space: nowrap;
		overflow: hidden;
		text-overflow: ellipsis;
	}
	.raffle_container{
		width: 100%;
		height: 100%;
		background-color: #fff;
		margin: 20upx 0;
		padding: 10upx;
		border-style: groove;
		border-width: 10upx;
		border-color:  #ffa500;
		.raffle_bar{
			width: 100%;
			display: flex;
			border-bottom: 0.5upx solid gray;
			padding: 10upx;
			.raffle_title_item{
				flex: 1;
				display: flex;
				justify-content: center;
				align-items: center;
				font-size: 40upx;
				color: #666;
				transition: all 0.3s;
			  
				&.active{
				  color: #915C43;
				  font-weight: bold;
				}
			}
		}
		
		.raffle_content{
			.raffle_records{
				padding: 10upx 0upx 10upx 0;
				.item_record{
					display: flex;
					align-items: center;
					justify-content: left;
					color: #915C43;
					background-color: #FEFBF6;
					padding: 20upx;
					margin-bottom: 15upx;
					.avatar_name{
						width: 124upx;
						height: 124upx;
						border-radius: 50%;
						// background-color: beige;
					}
					.detail{
						margin: 10upx 10upx 20upx 10upx;
						width:430upx;
						.desc{
							font-size: 25upx;
							margin-top: 20upx;
							font-weight: 400;
							margin-left:20upx;
							width: 400upx;
						}
						.nametime{
							display: flex;
							align-items: center;
							justify-content: left;
							text-align: center;
							.name{
								font-size: 30upx;
								font-weight: bold;
								width: 160upx;
								max-width: 200upx;
							}
							.time{
								font-size: 28upx; 
								margin-left: 20upx;
								width: 400upx;
								background-color: #F9EEDA;
								border-radius: 40upx;
								font-weight: 400;
							}
						}
					}
					.product{
						// background-color: gray;
						height: 120upx;
						width: 120upx;
						margin-left: 10upx;
					}
				}
			}
			.raffle_task{
				padding: 10upx 0upx 10upx 0;
				.item_task{
					display: flex;
					align-items: center;
					justify-content: space-between;
					color: #915C43;
					background-color: #FEFBF6;
					padding: 20upx;
					margin-bottom: 15upx;
					.detail{
						flex: 1;
						margin: 10upx 30upx 10upx 20upx;
						.title{
							font-size: 30upx;
							font-weight: bold;
							width: 300upx;
							max-width: 400upx;
						}
						.desc{
							font-size: 25upx;
							margin-top: 20upx;
							font-weight: 400;
							width: 350upx;
						}
					}
					.task_btn{
						min-width: 160upx;
						height: 60upx;
						line-height: 60upx;
						padding: 0 30upx;
						font-size: 26upx;
						border-radius: 30upx;
						background: #4caf50;
						color: #fff;
						transition: all 0.3s;
						&.disabled{
							background: #ccc !important;
							color:  #666 !important;
						}
					}
				}
			}
		}
	}
	.rules-content {
	  background-color:  ‌#E2758C !important;
	  border-radius: 16upx;
	  padding: 30urpx;
	  min-height: 650upx;
	  max-height: 80vh;
	}
	rule-time{
		padding:10upx;
	}
	.rule-text {
	  color: #915C43;
	  font-size: 35upx;
	  flex: 1;
	}
	.loading_text{
		text-align: center;
		padding: 30upx;
		color: #666;
	}
</style>